/*
 * $Id: PersistentSession.java
 * Created on 2004-12-28 14:53:27
 */
package cn.donave.framework.hibernate;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import cn.donave.framework.hibernate.set.DefaultSessionFactory;

/**
 * 
 * @author Duhengfei
 * @version $Revision: 2.0
 */
public final class PersistentSession implements Serializable {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	private static final ThreadLocal mSession = new ThreadLocal();

	private static SessionFactory sessionFactory;

	static {
		try {
			PersistentSessionFactory factory = new DefaultSessionFactory();
			sessionFactory = factory.getSessionFactory();
			System.out.println("================" + sessionFactory);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public static Session currentSession() throws HibernateException {
		Session s = (Session) mSession.get();
		if (s == null) {
			try {
				s = sessionFactory.openSession();
			} catch (HibernateException e) {
				throw new RuntimeException();
			}
			mSession.set(s);
		}
		if (!s.isOpen()) {
			// try {
			// s.reconnect();
			// } catch (HibernateException e) {
			// LogHelper.logError(e, PersistentSession.class.getName());
			// throw new RuntimeException();
			// }
		}
		return s;
	}

	@SuppressWarnings("unchecked")
	public static void closeSession() throws HibernateException {
		Session s = (Session) mSession.get();
		if (s == null)
			return;
		mSession.set(null);
		if (s != null) {
			try {
				s.close();
			} catch (HibernateException e) {
				e.printStackTrace();
			}
		}

	}

}